package com.opengroupe.recognize;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

/**
 * La capture de l'image pour le traitement ocr.
 * @author HAM11235
 *
 */
public class MainActivity extends Activity {

	final static String LOG_TAG = "Main_Activity";
	public SurfaceView surface_view;
	public Camera mCamera;
	SurfaceHolder.Callback sh_ob = null;
	SurfaceHolder surface_holder = null;
	SurfaceHolder.Callback sh_callback = null;
	static final int REQUEST_ACCOUNT_PICKER = 1;
	static final int REQUEST_AUTHORIZATION = 2;
	public static Drive service;
	public static GoogleAccountCredential credential;
	public static String filename;
	public static Context context;
	public static String ifFileInDrive;
	Builder alertDialog ;
	/**
	 * creation de l'application.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		alertDialog = new AlertDialog.Builder(this);
//		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//      setContentView(R.layout.search_screen);
		setContentView(R.layout.activity_main);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		surface_view = (SurfaceView) findViewById(R.id.surfaceView1);
		if (surface_holder == null) {
			surface_holder = surface_view.getHolder();
			surface_holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		sh_callback = my_callback();
		surface_holder.addCallback(sh_callback);
		List<String> list = new ArrayList<String>();
		list.add(DriveScopes.DRIVE);
		credential = GoogleAccountCredential.usingOAuth2(this, list);
		startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
		context = this.getApplicationContext();
	}

	@Override
	protected void onPause() {
		super.onPause();
		alertDialog = new AlertDialog.Builder(this);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		alertDialog = new AlertDialog.Builder(this);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		alertDialog = new AlertDialog.Builder(this);
	}
	/**
	 * Capture du résultat du sélection du compte Google.
	 */
	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT_PICKER:
			if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
				String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				if (accountName != null) {
					credential.setSelectedAccountName(accountName);
					service = getDriveService(credential);
				}
			}
			break;
		case REQUEST_AUTHORIZATION:
			if (resultCode == Activity.RESULT_OK) {
				saveFileToDrive();
			} else {
				startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
			}
			break;
		}
	}
	
	/**
	 * L'action à exécuter lors d'un clic sur le bouton de capture d'image.
	 * @param view
	 */
	public void onClick(View view) {
		java.io.File pictureFileDir = PhotoHandler.getDir();
		if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
			Log.d(LOG_TAG, "Impossible de creer le dossier pour enregistrer l'image.");
			return;
		}
		Camera.Parameters p = mCamera.getParameters();
		p.set("jpeg-quality", 100);
		p.setRotation(90);
		p.setJpegQuality(70);
		p.setJpegThumbnailQuality(70);
//		p.setJpegThumbnailSize(width, height);
		p.setPictureSize(640,480);
		p.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
		mCamera.setParameters(p);
		mCamera.takePicture(null, null, new PhotoHandler(getApplicationContext()));
		saveFileToDrive();
	}

	/**
	 * Enregistrement de l'image sur le drive et récupération du résultat du traitement ocr 
	 * et les autres informations sur le fichier sur le drive.
	 */
	private void saveFileToDrive() {
		
		alertDialog.setTitle("Traitement en cour")
	    .setMessage("Veuillez patienter pendant le traitement de l'image. Merci.")
	    .setPositiveButton("Close", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) { 
	            // Nothing to do.
	        }
	     })
//	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
//	        public void onClick(DialogInterface dialog, int which) { 
//	            // do nothing
//	        }
//	     })
	     .show();
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
//					java.io.File fileContent = new java.io.File(Environment.getExternalStorageDirectory().getPath() + 
//							java.io.File.separator + "Pictures" + java.io.File.separator + "recognize" +  java.io.File.separator + "se_ct_3.jpg"); //Pour Test
					java.io.File fileContent = new java.io.File(filename); //décommenter pour fnctionnement réel.
					FileContent mediaContent = new FileContent("image/jpeg", fileContent);
					File file = new File();
					file.setTitle(fileContent.getName());
					file.setMimeType("image/jpeg");
					Drive.Files.Insert dfi = service.files().insert(file, mediaContent);
					dfi.setOcr(true);
					File dfiFile = dfi.execute();
					if (dfiFile != null) {
						String imageAsTextUrl = dfiFile.getExportLinks().get("text/plain");
						HttpRequest req = service.getRequestFactory().buildGetRequest(new GenericUrl(imageAsTextUrl)); 
						req.setContentLoggingLimit(0);
						HttpResponse resp = req.execute();
						InputStream  is = resp.getContent();
		                StringBuffer sb = new StringBuffer();
		                BufferedReader in = null;
		                try {
		                    in = new BufferedReader(new InputStreamReader(is));
		                    String str;
		                    while ((str = in.readLine()) != null) {
		                        sb.append(str);
		                    }
		                } finally {
		                    if (in != null) {
		                        in.close();
		                    }
		                }
						Log.i(LOG_TAG, sb.toString().substring(17, sb.length()));
						Intent intent = new Intent(context, ResultScanActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("idFile", dfiFile.getId());
						intent.putExtra("ocr", sb.toString().substring(17, sb.length()));
						context.startActivity(intent);
					} else {
						ifFileInDrive = null;
						Log.w(LOG_TAG, "There is no file uploaded.");
					}
				} catch (UserRecoverableAuthIOException e) {
					startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	SurfaceHolder.Callback my_callback() {
		SurfaceHolder.Callback ob1 = new SurfaceHolder.Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				mCamera.stopPreview();
				mCamera.release();
				mCamera = null;
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {

				mCamera = Camera.open();
				Camera.Parameters p = mCamera.getParameters();
				p.setRotation(90);
				p.setJpegQuality(100);
				p.setJpegThumbnailQuality(100);
				p.setPictureSize(640,480);
				p.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
				mCamera.setParameters(p);
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
					mCamera.setDisplayOrientation(90);
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
					mCamera.setDisplayOrientation(180);
				try {
					mCamera.setPreviewDisplay(holder);
				} catch (IOException exception) {
					mCamera.release();
					mCamera = null;
				}
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				mCamera.startPreview();
			}
		};
		return ob1;
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() { 
				Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	public static Drive getService() {
		return service;
	}
	
	private Drive getDriveService(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
				//setApplicationName(APPLICATION_NAME).build();
	}

}
